package grailsforum

class ThreadsController {

    static allowedMethods = [

            deleteThread: 'POST'
    ]


    def view(){

        def t = Thread.get(params.id)

        if(t){
            [thread: t]
        }
        else{
            redirect(controller: 'courses', action: 'index')
        }
    }

    def add(){

        render (view: 'add', model: [course: params.id, tags: Tag.getAll()])
    }

    def doAdd(){

        Thread thread = new Thread(
                course: Course.get(params.course),
                name: params.name,
                created: new Date()
        )

        params.tags.each{

            Tag tag = Tag.get(it);
            thread.addToThreadTags(new ThreadTag(tag: tag, thread : thread))
        }

        Post post = new Post(
                position: 0,
                date    : new Date(),
                text    : params.question,
                thread  : thread,
                user    : session.user
        )

        if (thread.validate() && post.validate()){

            thread.addToPosts(post)
            thread.save()

            redirect(controller: 'threads', action: 'view', params: [id : Thread.last().id])
            return;
        }

        if (thread.errors.allErrors.size() > 0){
            flash.message = message(error: thread.errors.allErrors.first())
        }
        else if (post.errors.allErrors.size() > 0){

            flash.message = message(error:  post.errors.allErrors.first())
        }

        redirect(action: 'add', params: [id: params.course])
    }

    def deleteThread(){

        Thread thread = Thread.get(params.thread);



        thread.delete()

        render "ok"
    }
}

